<?php

namespace App\Http\Controllers;

use App\Models\RegisterVerifyLog;
use Illuminate\Support\Facades\Log;

use function AlibabaCloud\Client\json;

/**
 * 发送短信模版
 */
class SendNoteTemplateController extends Controller
{
    public $username = 'beitukejihy'; //用户名
    public $password = 'D0L)EVqz'; //原始密码
    // public $noteObj = null;
    // public function __construct()
    // {
    //     $this->validate = new SendNoteCodeValidate();
    //     $this->model = new RegisterVerify();
    //     $this->noteObj = new SendTemplateSMS();
    // }


    /**
     * 模板短信发送
     * @param signature     已报备的签名
     * @param tpId     模板id
     * @param ext   扩展号。纯数字，最多8位。
     * @param time   发送时间。若为空，立即发送；若不为空，设置定时字符串日期，定时时间必须大于当前时间，格式：yyyy-MM-dd HH:mm:ss ，例：2020-01-01 09:00:00。
     * @param records  List 模板变量信息集合，非变量2000个，变量最大200
     * @param      records.mobile  List 单个手机号码
     * @param      records.tpContent  JSON 需要替换的变量JSON
     * @param send_time null 表示立即发送
     */
    public function sendTemplateVerify($mobile, $verify_code, $signature, $template_id, $send_time = null)
    {
        //验证发送次数
        $registerVerifyLogModel = new RegisterVerifyLog;
        $verify_send_number = $registerVerifyLogModel->verifySendNumber($mobile, 10);
        if ($verify_send_number !== true) {
            return $verify_send_number;
        }

        $url = 'https://api-shss.zthysms.com/v2/sendSmsTp';
        $tKey = time();
        $data = [
            'username' => $this->username,
            'password' => md5(md5($this->password) . $tKey),
            'tKey' => $tKey,
            'signature' => $signature,
            'tpId' => $template_id,
            'time' => $send_time,
            'records' => [
                [
                    'mobile' => $mobile,
                    'tpContent' => [
                        'valid_code' => $verify_code,
                    ],
                ],
            ],
        ];
        $res = request_url($url, json_encode($data), 10, true);
        $res = json_decode($res, true);
        if ($res['code'] == 200) {
            $registerVerifyLogModel->addVerifyLog($mobile); //添加今日发送记录

            return true; //发送成功
        } else {
            Log::error('短信发送失败');
            Log::error($data);
            Log::error($res);
            return '发送失败-' . $res['msg'] . '-' . $res['code']; //发送失败
        }
    }
}
